﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Abhimanu.Mobile.Models;
using Abhimanu.Mobile.DB;

namespace Abhimanu.Mobile.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult StudentLogOn()
        {
            if (Request.Cookies.AllKeys.Contains("student"))
            {
                return RedirectToAction("Home", "Student");
            }
            else
            {
                return View();
            }
        }

        public ActionResult FacultyLogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult StudentLogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        List<DB.UserInfo> result = dataContext.UserInfos.Where(obj => (obj.EmailID == model.EmailID && obj.Password == model.Password && obj.LoginType == "S")).ToList();
                        if (result.Count > 0)
                        {
                            //FormsAuthentication.SetAuthCookie(result[0].FirstName, true, "student");
                            Response.Cookies.Add(new HttpCookie("student", SessionInfo.SetSession(result[0].UserID, result[0].FirstName)));
                            Response.Cookies[0].Expires = DateTime.Now.AddHours(1);
                            return RedirectToAction("Home", "Student");
                        }
                        else
                        {
                            ModelState.AddModelError("", "The user name or password provided is incorrect.");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [HttpPost]
        public ActionResult FacultyLogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        List<DB.UserInfo> result = dataContext.UserInfos.Where(obj => (obj.EmailID == model.EmailID && obj.Password == model.Password && obj.LoginType == "F")).ToList();
                        if (result.Count > 0)
                        {
                            //FormsAuthentication.SetAuthCookie(result[0].FirstName, true);
                            Response.Cookies.Add(new HttpCookie("faculty", SessionInfo.SetSession(result[0].UserID, result[0].FirstName)));
                            Response.Cookies[0].Expires = DateTime.Now.AddHours(1);
                            return RedirectToAction("Home", "Faculty");
                        }
                        else
                        {
                            ModelState.AddModelError("", "The user name or password provided is incorrect.");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult StudentLogOff()
        {
            //FormsAuthentication.SignOut();
            Response.Cookies["student"].Expires = DateTime.Now.AddHours(-1);

            return RedirectToAction("StudentLogOn", "Account");
        }

        public ActionResult FacultyLogOff()
        {
            //FormsAuthentication.SignOut();
            Response.Cookies["faculty"].Expires = DateTime.Now.AddHours(-1);

            return RedirectToAction("FacultyLogOn", "Account");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        DB.UserInfo userInfo = new DB.UserInfo()
                        {
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            EmailID = model.Email,
                            Password = model.Password,
                            RegistrationNo = model.RegistrationNo,
                            YearOfAdmission = Convert.ToInt32(model.AdmissionYear),
                            SelectCenter = model.Center,
                            CreatedDate = DateTime.Now,
                            LastModifiedDate = DateTime.Now,
                            LoginType = "S"
                        };

                        dataContext.UserInfos.InsertOnSubmit(userInfo);
                        dataContext.SubmitChanges();
                        //FormsAuthentication.SetAuthCookie(model.FirstName, true);
                        Response.Cookies.Add(new HttpCookie("student", SessionInfo.SetSession(userInfo.UserID, userInfo.FirstName)));
                        Response.Cookies["student"].Expires = DateTime.Now.AddHours(1);
                        return RedirectToAction("Home", "Student");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while registering!");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult FacultyProfileHome()
        {
            return View();
        }

        public ActionResult FacultyProfileUpdate()
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            Profile model = new Profile();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var result = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList();
                if (result.Count > 0)
                {
                    model = new Profile()
                    {
                        AdmissionYear = result[0].YearOfAdmission.ToString(),
                        Center = result[0].SelectCenter,
                        Email = result[0].EmailID,
                        FirstName = result[0].FirstName,
                        LastName = result[0].LastName,
                        RegistrationNo = result[0].RegistrationNo,
                    };
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult FacultyProfileUpdate(Profile model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        UserInfo userInfo = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList()[0];
                        userInfo.FirstName = model.FirstName;
                        userInfo.LastName = model.LastName;
                        userInfo.YearOfAdmission = Convert.ToInt32(model.AdmissionYear);
                        userInfo.SelectCenter = model.Center;
                        userInfo.EmailID = model.Email;
                        userInfo.RegistrationNo = "0";

                        dataContext.SubmitChanges();
                        return RedirectToAction("FacultyProfileHome", "Account");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while updating profile info!");
                }
            }

            return View(model);
        }

        public ActionResult FacultyUpdatePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FacultyUpdatePassword(ChangePassword model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("faculty"))
            {
                return RedirectToAction("FacultyLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["faculty"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        UserInfo userInfo = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList()[0];

                        if (userInfo.Password == model.OldPassword)
                        {
                            userInfo.Password = model.NewPassword;

                            dataContext.SubmitChanges();
                            return RedirectToAction("FacultyProfileHome", "Account");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Invalid old password!");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while updating profile info!");
                }
            }

            return View(model);
        }

        public ActionResult StudentProfileHome()
        {
            return View();
        }

        public ActionResult StudentProfileUpdate()
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("student"))
            {
                return RedirectToAction("StudentLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["student"].Value).UserID;
            }

            Profile model = new Profile();
            using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
            {
                var result = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList();
                if (result.Count > 0)
                {
                    model = new Profile()
                    {
                        AdmissionYear = result[0].YearOfAdmission.ToString(),
                        Center = result[0].SelectCenter,
                        Email = result[0].EmailID,
                        FirstName = result[0].FirstName,
                        LastName = result[0].LastName,
                        RegistrationNo = result[0].RegistrationNo,
                    };
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult StudentProfileUpdate(Profile model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("student"))
            {
                return RedirectToAction("StudentLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["student"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        UserInfo userInfo = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList()[0];
                        userInfo.FirstName = model.FirstName;
                        userInfo.LastName = model.LastName;
                        userInfo.YearOfAdmission = Convert.ToInt32(model.AdmissionYear);
                        userInfo.SelectCenter = model.Center;
                        userInfo.EmailID = model.Email;
                        userInfo.RegistrationNo = model.RegistrationNo;

                        dataContext.SubmitChanges();
                        return RedirectToAction("StudentProfileHome", "Account");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while updating profile info!");
                }
            }

            return View(model);
        }

        public ActionResult StudentUpdatePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult StudentUpdatePassword(ChangePassword model)
        {
            long userId = 0;
            if (!Request.Cookies.AllKeys.Contains("student"))
            {
                return RedirectToAction("StudentLogOn", "Account");
            }
            else
            {
                userId = SessionInfo.GetSessionInfo(Request.Cookies["student"].Value).UserID;
            }

            if (ModelState.IsValid)
            {
                try
                {
                    using (DB.AbhimanuDataContext dataContext = new DB.AbhimanuDataContext())
                    {
                        UserInfo userInfo = dataContext.UserInfos.Where(obj => (obj.UserID == userId)).ToList()[0];

                        if (userInfo.Password == model.OldPassword)
                        {
                            userInfo.Password = model.NewPassword;

                            dataContext.SubmitChanges();
                            return RedirectToAction("StudentProfileHome", "Account");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Invalid old password!");
                        }
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "Error while updating profile info!");
                }
            }

            return View(model);
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
